<template>
  <div class="user-management">

    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable
              class="status-select"
            >
              <el-option :value="0" label="正常">
                <template #default>
                  <div class="status-option">
                    <el-tag type="success" effect="plain" size="small">正常</el-tag>
                  </div>
                </template>
              </el-option>
              <el-option :value="1" label="封禁">
                <template #default>
                  <div class="status-option">
                    <el-tag type="danger" effect="plain" size="small">封禁</el-tag>
                  </div>
                </template>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button @click="onSubmitEmpty">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" fixed="left" />
        <el-table-column prop="username" label="用户名称" min-width="120" />
        <el-table-column prop="email" label="用户邮箱" min-width="180" />
        <el-table-column prop="createTime" label="注册日期" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '正常' : '封禁' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="showUserDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      title="用户详情"
      width="35%"
    >
      <div v-if="currentUser" class="user-detail">
        <p><strong>用户ID：</strong>{{ currentUser.id }}</p>
        <p><strong>用户名称：</strong>{{ currentUser.username }}</p>
        <p><strong>用户邮箱：</strong>{{ currentUser.email }}</p>
        <p><strong>注册日期：</strong>{{ formatDate(currentUser.createTime) }}</p>
        <p><strong>最后登录时间：</strong>{{ formatDateTime(currentUser.lastLoginTime) }}</p>
        <p><strong>状态：</strong>
          <el-tag :type="currentUser.status === 0 ? 'success' : 'danger'">
            {{ currentUser.status === 0 ? '启用' : '禁用' }}
          </el-tag>
        </p>
        
        <!-- 封禁信息，仅在用户被封禁时显示 -->
        <template v-if="currentUser.status === 1">
          <div class="ban-info">
            <h4>封禁信息</h4>
            <p><strong>封禁总时长：</strong>{{ hoursToDisplay(currentUser.banDuration) }}</p>
            <p><strong>剩余时长：</strong>{{ hoursToDisplay(currentUser.banTimeLeft) }}</p>
            <p><strong>操作管理员：</strong>{{ currentUser.banAdminName }}</p>
            <p><strong>封禁原因：</strong>{{ currentUser.banReason }}</p>
          </div>
        </template>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <!-- 根据用户状态显示不同的按钮 -->
          <el-button 
            v-if="currentUser?.status === 1"
            type="primary"
            @click="showUnbanDialog"
          >解除封禁</el-button>
          <el-button 
            v-else
            type="danger"
            @click="showBanDialog"
          >封禁用户</el-button>
          <el-button @click="userDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 封禁用户对话框 -->
    <el-dialog
      v-model="banDialogVisible"
      title="封禁用户"
      width="40%"
      append-to-body
    >
      <!-- 如果有封禁历史，显示历史记录 -->
      <div v-if="currentUser?.banHistory?.length" class="ban-history">
        <div class="ban-history-header">
          <span class="title">封禁历史记录</span>
          <span class="count">共 {{ currentUser.banHistory.length }} 条记录</span>
        </div>
        <el-table 
          :data="currentUser.banHistory" 
          style="width: 100%" 
          size="small"
          :border="true"
          stripe
        >
          <el-table-column prop="banTime" label="封禁时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.banTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="封禁时长" width="100">
            <template #default="scope">
              <span :class="scope.row.duration === null ? 'permanent-ban' : ''">
                {{ hoursToDisplay(scope.row.duration) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="adminName" label="操作管理员" width="120" />
          <el-table-column prop="reason" label="封禁原因" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag 
                :type="scope.row.status === 0 ? 'info' : 'danger'" 
                size="small"
                effect="plain"
              >
                {{ scope.row.status === 0 ? '已解封' : '已封禁' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-divider v-if="currentUser?.banHistory?.length" content-position="left">新增封禁</el-divider>

      <el-form :model="banForm" label-width="100px" class="ban-form">
        <el-form-item label="封禁时长" class="ban-form-item">
          <el-select 
            v-model="banForm.duration" 
            placeholder="请选择封禁时长"
          >
            <template #default>
              <el-option 
                v-for="option in banOptions" 
                :key="option.value" 
                :label="option.label"
                :value="option.value"
              />
            </template>
            <template #selected>
              <span>{{ banForm.duration === null ? '永久' : banForm.duration ? `${Math.floor(banForm.duration / (24 * 60 * 60))}天` : '' }}</span>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="封禁原因" class="ban-form-item">
          <el-input
            v-model="banForm.reason"
            type="textarea"
            rows="3"
            placeholder="请输入封禁原因"
          />
        </el-form-item>
        <el-form-item label="验证码" class="ban-form-item">
          <el-input v-model="banForm.verificationCode" placeholder="请输入验证码" style="width: calc(100% - 120px); display: inline-block;" />
          <el-button 
            @click="getVerificationCode" 
            style="width: 100px; margin-left: 10px;"
            :disabled="countdown > 0"
          >
            {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="banDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBan">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 解除封禁对话框 -->
    <el-dialog
      v-model="unbanDialogVisible"
      title="解除封禁"
      width="360px"
      append-to-body
    >
      <div class="unban-dialog-content">
        <el-form :model="unbanForm" label-width="0">
          <el-form-item>
            <div class="verification-code-wrapper">
              <el-input 
                v-model="unbanForm.verificationCode" 
                placeholder="请输入验证码"
                maxlength="6"
                class="verification-input"
              />
              <el-button 
                type="primary" 
                class="get-code-btn"
                @click="getVerificationCode"
                :disabled="countdown > 0"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="unbanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUnban">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserList, 
  updateUserStatus,
  getBanVerificationCode,
  getUnbanVerificationCode 
} from '@/api/admin'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userDialogVisible = ref(false)
const currentUser = ref(null)
const editDrawerVisible = ref(false)
const editingUser = ref(null)
const banDialogVisible = ref(false)
const banForm = ref({
  duration: null as number | null,
  reason: '',
  verificationCode: ''
})

const unbanForm = ref({
  verificationCode: ''
})

const banOptions = [
  { label: '1天', value: 24 * 60 * 60 },
  { label: '3天', value: 72 * 60 * 60 },
  { label: '7天', value: 168 * 60 * 60 },
  { label: '15天', value: 360 * 60 * 60 },
  { label: '30天', value: 720 * 60 * 60 },
  { label: '永久', value: null }
]

const displayDuration = computed(() => {
  if (banForm.value.duration === null) return '永久'
  if (!banForm.value.duration) return ''
  return `${Math.floor(banForm.value.duration / (24 * 60 * 60))}天`
})

const searchForm = ref({
  username: '',
  email: '',
  status: ''
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  const d = new Date(datetime)
  const date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  const time = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
  return `${date} ${time}`
}

// 获取用户列表
const getUsersList = async () => {
  try {
    const params = {
      username: searchForm.value.username,
      email: searchForm.value.email,
      status: searchForm.value.status,
      page: currentPage.value.toString(),
      pageSize: pageSize.value.toString()
    }
    
    const res = await getUserList(params)
    console.log(res)
    if (res.code === 0) {
      tableData.value = res.data.results.map(item => ({
        id: item.userId,
        username: item.username,
        email: item.email,
        createTime: item.createTime,
        lastLoginTime: item.lastLoginTime,
        status: item.status,
        banDuration: item.banDuration,
        banTimeLeft: item.banTimeLeft,
        banAdminName: item.banAdminName,
        banReason: item.banReason,
        banHistory: item.banHistory
      }))
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错：', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getUsersList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUsersList()
}

// 搜索和重置
const onSubmit = () => {
  currentPage.value = 1
  getUsersList()
}

const onSubmitEmpty = () => {
  searchForm.value.username = ''
  searchForm.value.email = ''
  searchForm.value.status = ''
  currentPage.value = 1
  getUsersList()
}

// 修改查看用户详情的方法
const showUserDetail = (row) => {
  currentUser.value = row
  userDialogVisible.value = true
}

// 显示封禁对话框
const showBanDialog = () => {
  banForm.value = {
    duration: null,
    reason: '',
    verificationCode: ''
  }
  banDialogVisible.value = true
}

// 处理封禁用户
const handleBan = async () => {
  if (banForm.value.duration === undefined) {
    ElMessage.warning('请选择封禁时长')
    return
  }
  if (!banForm.value.reason) {
    ElMessage.warning('请输入封禁原因')
    return
  }
  if (!banForm.value.verificationCode) {
    ElMessage.warning('请输入验证码')
    return
  }

  try {
    const banDTO = {
      status: 1,  // 1表示封禁
      banReason: banForm.value.reason,
      banDuration: banForm.value.duration  // 直接使用秒为单位的时长
    }
    const verifyDTO = {
      verificationCode: banForm.value.verificationCode
    }

    const res = await updateUserStatus(currentUser.value.id, banDTO, verifyDTO)
    if (res.code === 0) {
      ElMessage.success('封禁成功')
      banDialogVisible.value = false
      userDialogVisible.value = false
      getUsersList()
    } else {
      ElMessage.error(res.msg || '封禁失败')
    }
  } catch (error) {
    console.error('封禁用户失败：', error)
    ElMessage.error(error.response?.data?.msg || '封禁失败')
  }
}

// 添加倒计时相关的状态
const countdown = ref(0)
const timer = ref(null)

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  timer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)
}

// 获取验证码
const getVerificationCode = async () => {
  // 如果正在倒计时，不允许重复获取
  if (countdown.value > 0) {
    return
  }

  try {
    if (!currentUser.value?.id) {
      ElMessage.error('用户ID不存在')
      return
    }

    // 根据当前操作类型调用不同的验证码接口
    const res = banDialogVisible.value 
      ? await getBanVerificationCode(currentUser.value.id)
      : await getUnbanVerificationCode(currentUser.value.id)
    
    if (res.code === 0) {
      ElMessage.success('验证码已发送到管理员邮箱')
      // 开始倒计时
      startCountdown()
    } else {
      ElMessage.error(res.msg || '获取验证码失败')
    }
  } catch (error) {
    console.error('获取验证码失败：', error)
    ElMessage.error('获取验证码失败')
  }
}

// 在组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

const handleUnban = async () => {
  if (!unbanForm.value.verificationCode) {
    ElMessage.warning('请输入验证码')
    return
  }

  ElMessageBox.confirm(
    '确定要解除该用户的封禁状态吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const banDTO = {
        status: 0  // 0表示正常
      }
      const verifyDTO = {
        verificationCode: unbanForm.value.verificationCode
      }

      const res = await updateUserStatus(currentUser.value.id, banDTO, verifyDTO)
      if (res.code === 0) {
        ElMessage.success('解除封禁成功')
        unbanDialogVisible.value = false
        userDialogVisible.value = false
        getUsersList()
      } else {
        ElMessage.error(res.msg || '解除封禁失败')
      }
    } catch (error) {
      console.error('解除封禁失败：', error)
      ElMessage.error('解除封禁失败')
    }
  })
}

// 添加时长转换函数
const hoursToDisplay = (seconds) => {
  if (seconds === null) return '永久'
  if (seconds < 60) return `${seconds}秒`
  if (seconds < 60 * 60) return `${Math.floor(seconds / 60)}分钟`
  if (seconds < 24 * 60 * 60) return `${Math.floor(seconds / (60 * 60))}小时`
  return `${Math.floor(seconds / (24 * 60 * 60))}天`
}

const unbanDialogVisible = ref(false)

const showUnbanDialog = () => {
  unbanForm.value.verificationCode = ''
  unbanDialogVisible.value = true
}

onMounted(() => {
  getUsersList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  width: 60px;
  text-align: center;
}

/* 添加表单样式 */
:deep(.el-form--inline .el-form-item) {
  margin-right: 30px;
}

:deep(.el-form-item__content) {
  margin-left: 20px;
}

:deep(.el-input) {
  width: 220px;
}

:deep(.el-dialog__body) {
  padding: 30px;
}

:deep(.el-dialog__body p) {
  margin: 15px 0;
  font-size: 14px;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 25px;
}

.user-detail p {
  margin: 12px 0;
  line-height: 1.8;
}

.ban-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.ban-info h4 {
  margin: 0 0 10px 0;
  color: #f56c6c;
}

:deep(.el-select) {
  width: 100%;
}

.ban-history {
  margin-bottom: 20px;
}

.ban-history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.ban-history-header .title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.ban-history-header .count {
  font-size: 13px;
  color: #909399;
}

.permanent-ban {
  color: #f56c6c;
  font-weight: 500;
}

:deep(.el-table--small) {
  font-size: 13px;
}

:deep(.el-table--border) {
  border-radius: 4px;
}

:deep(.el-table--striped) {
  background-color: #fafafa;
}

:deep(.el-divider__text) {
  font-size: 15px;
  font-weight: 500;
  color: #606266;
}

.status-select {
  width: 120px !important;
}

.status-option {
  padding: 4px 0;
}

.status-option .el-tag {
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 2px 8px;
  margin: 0;
}

:deep(.el-select-dropdown__item) {
  padding: 0 12px;
}

/* 覆盖全局标签样式 */
:deep(.el-tag) {
  width: auto;
  min-width: 60px;
  text-align: center;
}

.unban-dialog-content {
  padding: 30px 20px 10px;
}

.verification-code-wrapper {
  display: flex;
  gap: 10px;
  align-items: center;
}

.verification-input {
  width: 180px;
}

.get-code-btn {
  flex-shrink: 0;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  margin-top: 0;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

/* 封禁表单样式 */
.ban-form {
  padding: 20px 0;
}

.ban-form-item {
  margin-bottom: 25px;
}

.ban-form-item:last-child {
  margin-bottom: 0;
}

:deep(.el-form-item__content) {
  margin-left: 20px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  min-height: 80px;
}
</style> 